<template>
    <div class="login">
    
      <el-form :model="ruleForm" status-icon :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
        <el-form-item label="用户名" prop="username">
        <el-input v-model.number="ruleForm.username"></el-input>
      </el-form-item>
      <el-form-item label="密码" prop="pass">
        <el-input type="password" v-model="ruleForm.pass" autocomplete="off"></el-input>
      </el-form-item>
     
    
      <el-form-item>
        <el-button type="primary" @click="submitForm('ruleForm')">提交</el-button>
        <el-button @click="resetForm('ruleForm')">重置</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
    export default {
         data() {
      var checkUser = (rule, value, callback) => {
        if (!value) {
          return callback(new Error('请输入用户名'));
        }else{
              callback();
        }

      };
      var validatePass = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('请输入密码'));
        } else {
          if (this.ruleForm.checkPass !== '') {
            this.$refs.ruleForm.validateField('checkPass');
          }
          callback();
        }
      };
      var validatePass2 = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('请再次输入密码'));
        } else if (value !== this.ruleForm.pass) {
          callback(new Error('两次输入密码不一致!'));
        } else {
          callback();
        }
      };
      return {
        ruleForm: {
          pass: '',
          username: ''
        },
        rules: {
          pass: [
            { validator: validatePass, trigger: 'blur' }
          ],
          checkPass: [
            { validator: validatePass2, trigger: 'blur' }
          ],
          username: [
            { validator: checkUser, trigger: 'blur' }
          ]
        }
      };
    },
    methods: {
        submitForm(formName){
            this.$refs[formName].validate((valid)=>{
                if(valid){
                    this.$store.dispatch("login",{username:this.ruleForm.username,password:this.ruleForm.pass}).then(res=>{
                        if(res.code==200){
                            this.$router.push('/')
                        }
                        else{
                            alert(res.msg)
                        }
                    })
                }
                else{
                    return false
                }
            });
        },
        resetForm(formName){
            this.$refs[formName].resetFields();
        }
    },
    }
</script>

<style lang="scss">
  .login{
    position: absolute;
    left:0;
    top:0;
    width:100vw;
    height: 100vh;
      background: rgb(27, 41, 87);
      z-index: 2;
      display: flex;
      justify-content: center;
      align-items:center;
    .el-form{
      background:rgba(255,255,255,.8);
      padding:30px;
      border-radius: 10px;

    }
  }

</style>